# -*- coding: utf-8 -*-

from random import randrange
import pygame

pygame.init()
width, height = 480, 480
screen = pygame.display.set_mode((width, height))
snake = [pygame.Rect(10, 10, 10, 10), pygame.Rect(10, 20, 10, 10)]

up = (0, -10)
down = (0, 10)
left = (-10, 0)
right = (10, 0)

dir = down
clock = pygame.time.Clock()
food = None
score = 0
font = pygame.font.SysFont('simhei', 20)

dead = False
while True:

    clock.tick(min(5 + (len(snake) / 4), 30))
    event = pygame.event.poll()
    if event.type == pygame.QUIT:
        pygame.quit()
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_UP and dir != down:
            dir = up
        if event.key == pygame.K_DOWN and dir != up:
            dir = down
        if event.key == pygame.K_LEFT and dir != right:
            dir = left
        if event.key == pygame.K_RIGHT and dir != left:
            dir = right

    screen.fill((255, 255, 255))

    if dead:
    	screen.fill((0, 0, 0))
    	surface = font.render(u"Game Over 分数:" + str(score), True, (255,255,255))
    	screen.blit(surface, (200, 0))

    if food is None:
        food = pygame.Rect(randrange(48) * 10, randrange(48) * 10, 10, 10)
    pygame.draw.rect(screen, (0, 0, 0), food)

    for rect in snake:
        pygame.draw.rect(screen, (0, 0, 0), rect)
    node = snake[-1].move(dir)

    if node in snake or node.left > width or node.top > height or node.left < 0 or node.top < 0:
    	dead = True
    if node == food:
        food = None
        score += 10
    else:
        del snake[0]

    snake.append(node)

    surface = font.render(u'分数'+str(score), True, (0,0,0))
    screen.blit(surface, (0, 0))

    pygame.display.flip()
